package com.example.blew.omp.system.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.Digester;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.blew.omp.system.mapper.UserMapper;
import com.example.blew.omp.system.model.ReturnModel;
import com.example.blew.omp.system.model.converter.UserConverter;
import com.example.blew.omp.system.model.form.UserForm;
import com.example.blew.omp.system.model.po.User;
import com.example.blew.omp.system.service.UserService;
import com.example.blew.omp.system.util.JwtUtils;
import com.example.blew.omp.system.util.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 1
 *
 * @author kk
 * @date 2023/7/8
 */
@Service
public class UserServiceImpl  extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private RedisUtil redisCache;


    @Override
    public Boolean save(UserForm userForm) {
        User user = UserConverter.converterToPoByFrom(userForm);
        checkValid(user);
        Digester digester = DigestUtil.digester("sm3");
        user.setUserPassword(digester.digestHex(user.getUserPassword()));
        boolean save = save(user);
        return save;
    }

    @Override
    public Boolean updateById() {
        return null;
    }

    @Override
    public ReturnModel login(UserForm userForm){
        String userName= userForm.getUserName();
        String userPasswd= userForm.getUserPassword();
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(StrUtil.isNotEmpty(userName),User::getUserName,userName);
        User user = getOne(queryWrapper, false);
        if(null== user){
            throw new RuntimeException("用户名不存在");
        }
        // 比对密码
        Digester digester = DigestUtil.digester("sm3");
        String passwd = digester.digestHex(userPasswd);
        if(passwd.equals(user.getUserPassword())){
            String token = JwtUtils.createToken(user.getId());
            redisCache.readWriteData("TOKEN_" + token, JSON.toJSONString(user), false);
            return ReturnModel.newSuccessInstance(token);
        }

        return ReturnModel.newFailureInstance();
    }

    @Override
    public User checkToken(String token) {
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        Map<String, Object> map = JwtUtils.checkToken(token);
        if (map == null) {
            return null;
        }
        String userJson =  redisCache.read(("TOKEN_" + token)).toString();
        if (StrUtil.isEmpty(userJson)) {
            return null;
        }
        User user = JSON.parseObject(userJson, User.class);
        return user;
    }



    private void checkValid(User user){

    }

}
